/*
 * $Id: JsonReadersContainer.java 80 2009-06-19 08:01:51Z donbeave $
 */

package labour.concept.client.data.json;

import java.util.HashMap;

import com.extjs.gxt.ui.client.data.DataReader;
import com.extjs.gxt.ui.client.data.JsonReader;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;

@SuppressWarnings("unchecked")
public class JsonReadersContainer implements DataReader<HashMap<String, Object>> {

  private String dataPath;
  private HashMap<String, JsonReader> readers;

  public JsonReadersContainer(String dataPath) {
    super();

    this.dataPath = dataPath;
    readers = new HashMap<String, JsonReader>();
  }

  @Override
  public HashMap<String, Object> read(Object loadConfig, Object data) {
    HashMap<String, Object> result = new HashMap<String, Object>();
    JSONObject jsonRoot = null;

    if (data instanceof JavaScriptObject) {
      jsonRoot = new JSONObject((JavaScriptObject) data);
    } else {
      jsonRoot = (JSONObject) JSONParser.parse((String) data);
    }

    JSONObject root = (JSONObject) jsonRoot.get(dataPath);

    for (String path : readers.keySet()) {
      JsonReader reader = readers.get(path);

      result.put(path, reader.read(loadConfig, root.get(path).isObject().getJavaScriptObject()));
    }

    return result;
  }

  public void registerReader(String path, JsonReader reader) {
    readers.put(path, reader);
  }

}
